node('master') {
    // modify node_name and ip address fields 取消[全局安全设置]-[防止跨站点请求伪造]//
    // ---------------------------------------//
    def node_name           = 'test-slave-label'
    //---------------------------------------//

    def agent_description   = 'test-slave-label'
    def install_location    =  '/home/yh/workspace/jenkins-agent'
    def executor_count      = '1'
    def slave_label         = 'test-slave-label'
    def cret ='jenkins_private_key'
    def host = '192.168.3.8'

    wrap([$class: 'MaskPasswordsBuildWrapper',
          varPasswordPairs: [[password: "${params.jenkins_user}", var: 'jenkins_user'],
                             [password: "${params.jenkins_pwd}", var: 'jenkins_pwd']]]){
        stage('Add Jenkins slave') {
            addNode(slave_label,executor_count,install_location);
        }

        stage('get Agent jar') {
            def url = params.jenkins_url + "/jnlpJars/agent.jar";
            getAgentjar(params.jenkins_user,params.jenkins_pwd,url);
        }

        stage('Delete Jenkins slave') {
            sh """
            echo hello world
            """
            createRemoteDir(cret, host, install_location)
            scpFileToNode(
                    params.jenkins_user ,
                    params.jenkins_pwd,
                    params.jenkins_url,
                    node_name,
                    install_location,
                    host)
            //deleteNode(node_name);
        }
    }
}

def execurl(jenkins_user,jenkins_pwd,groovy_script){
    sh "curl --user '${jenkins_user}:${jenkins_pwd}' --data-urlencode  'script=${groovy_script}' -X POST '${jenkins_url}'/scriptText"
}

def deleteNode(nodeName){
    def groovy_script = """
       Node node = Jenkins.instance.getNode(\"${nodeName}\")
       println("---- Shutting down node ----!");
       node.getComputer().setTemporarilyOffline(true,null);
       node.getComputer().doDoDelete();
       """
    execurl(params.jenkins_user,params.jenkins_pwd,groovy_script);
}

def deleteOfflineNode(nodeName){
    def groovy_script = """
            for (Node aSlave in Jenkins.instance.getNodes()) {
            println("");
            println("==========");
            println("Name: " + aSlave.name);
            println("computer.isOffline: " + aSlave.getComputer().isOffline());
            println("computer.getLog: " + aSlave.getComputer().getLog());
            println("computer.getBuilds: " + aSlave.getComputer().getBuilds());
            if (aSlave.getComputer().isOffline()) {
              println("----- Shutting down node -----!");
              aSlave.getComputer().setTemporarilyOffline(true,null);
              aSlave.getComputer().doDoDelete();
            }
        }
       """
        execurl(params.jenkins_user,params.jenkins_pwd,groovy_script);
}

def addNode(node_name,executor_count,install_location){
    def groovy_script = """ 
               import hudson.model.Node.Mode
               import hudson.slaves.*
               import jenkins.model.Jenkins
               DumbSlave slave = new DumbSlave(
                                    \"${node_name}\",
                                    \"${node_name}\",
                                    \"${install_location}\",
                                    \"${executor_count}\",
                                    Node.Mode.NORMAL,
                                    \"${node_name}\",
                                    new JNLPLauncher(),
                                    RetentionStrategy.INSTANCE)
                Jenkins.instance.addNode(slave)
                """
    execurl(params.jenkins_user,params.jenkins_pwd,groovy_script);
}

def getAgentjar(jenkins_user,jenkins_pwd,url){
     sh """
     curl --user '${jenkins_user}:${jenkins_pwd}'  '${url}' -o agent.jar
     pwd
     ls
     """
}

def createRemoteDir(cret,host,dir){
    sshagent (credentials: [cret]) {
        sh "ssh -o StrictHostKeyChecking=no ${host} mkdir -p ${dir}/remoting"
    }
}

def scpFileToNode(jenkins_user,jenkins_pwd,jenkins_url,node_name,workDir,host){
    def secretKey = sh(script: "curl --user '${jenkins_user}:${jenkins_pwd}' -X GET '${jenkins_url}'/computer/'${node_name}'/slave-agent.jnlp | sed \"s/.*<application-desc main-class=\\\"hudson.remoting.jnlp.Main\\\"><argument>\\([a-z0-9]*\\\\).*/\\1/\"",returnStdout: true).trim()
    println(secretKey)
    println("")
    sh """
      echo 'nohup java -jar ${workDir}/agent.jar -jnlpUrl ${jenkins_url}/computer/${node_name}/slave-agent.jnlp -secret ${secretKey} -workDir \"${workDir}\" -failIfWorkDirIsMissing > log 2>&1 &' > start.sh
      ls
      chmod 755 start.sh
      scp agent.jar start.sh ${host}:${workDir}
      ssh -o StrictHostKeyChecking=no ${host} chown -R yh:yh ${workDir}
      ssh -o StrictHostKeyChecking=no ${host} < \"start.sh\"
    """
}
